package com.gexin.controller.system.weixin;

import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gexin.common.utils.StringUtil;
import com.gexin.core.web.SystemBaseController;
import com.gexin.model.weixin.WeixinAppConfig;
import com.gexin.model.weixin.WeixinUser;
import com.gexin.weixin.kit.WxConfigKit;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.log.Log;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.UserApi;
/**
 * 后台管理员模板
 * @author 肖得明
 *  新增的时候复制这个
 */
@ControllerBind(controllerKey = "/system/weixin/userlist", viewPath = "WEB-INF/system/weixin/")
public class WeiXinUserController extends SystemBaseController {
	private static final Log  log =  Log.getLog(WeiXinUserController.class);
	//首页
	public void index(){
		List<WeixinAppConfig> appConfig=WeixinAppConfig.dao.find(" select * from t_weixin_app_config ");
		setAttr("wxAppConfigs", appConfig);
		render("wx_user_list.html");
	}
	
	public void query(){
		WeixinUser user=new WeixinUser();
		user.setNickname(getPara("nickname"));
		user.setSex(getParaToInt("sex",null));
		String appConfigId=getPara("appConfigId",null);
		renderJson(WeixinUser.dao.paginate(getpage(), getpageSize(),user,appConfigId));
	}
	
	/**
	 * 微信同步粉丝
	 */
	public void sync_user() {
		Integer id=getParaToInt("id",null);
		List<WeixinAppConfig> weixinAppConfigs=WeixinAppConfig.dao.findByIdOrGetAll(id);
		if (weixinAppConfigs.size()>0) {
			for (WeixinAppConfig weixinAppConfig : weixinAppConfigs) {
					ApiConfig apiConfig=WxConfigKit.getApiConfig(weixinAppConfig.getId());
					ApiConfigKit.setThreadLocalAppId(apiConfig.getAppId());
					ApiResult apiResult=UserApi.getFollowers(null);
					JSONObject jsonObject =JSONObject.parseObject(apiResult.getJson());
					String next_openid =  jsonObject.getString("next_openid"); 
					while(StringUtil.isNotEmpty(next_openid)){
						JSONArray openids= jsonObject.getJSONObject("data").getJSONArray("openid");
						for(int i=0;i<openids.size();i++){
							String openid =openids.get(i).toString();  
							ApiResult apiResults = UserApi.getUserInfo(openid);
							WeixinUser  user =	WeixinUser.dao.paseWxUser(apiResults);
							user.setAppid(weixinAppConfig.getId());
							try {
								user.save();
							} catch (Exception e) {
								log.error("保存昵称错误:"+user.getNickname());
								user.setNickname("none");
								user.save();
							}
						}
						
						if(!StringUtil.show(next_openid).equals("")){
							 apiResult = UserApi.getFollowers(jsonObject.getString("next_openid"));
							 jsonObject =JSONObject.parseObject(apiResult.getJson());
							 next_openid =  jsonObject.getString("next_openid"); 
						 }
					}
			  }	
		}
		success();
	}
	
}


